package Text6;

import java.util.*;

public class Main {
    public static int N = 150010, n, m, idx;
    public static int[] h = new int[N];
    public static int[] e = new int[N];
    public static int[] ne = new int[N];
    public static int[] w = new int[N];
    public static int[] dist = new int[N];
    public static boolean[] st = new boolean[N];

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        m = in.nextInt();
        Arrays.fill(h, -1);
        Arrays.fill(dist, 0x3f3f3f3f);
        dist[1] = 0;
        for (int i = 0; i < m; i++) {
            int a = in.nextInt();
            int b = in.nextInt();
            int c = in.nextInt();
            add(a, b, c);
        }
        System.out.println(dijkstra());
    }

    private static void add(int a, int b, int c) {
        e[idx] = b;
        w[idx] = c;
        ne[idx] = h[a];
        h[a] = idx++;
    }

    private static int dijkstra() {
        PriorityQueue<PII> piis = new PriorityQueue<>();
        piis.offer(new PII(dist[1], 1));
        while (!piis.isEmpty()) {
            PII tmp = piis.poll();
            int ver = tmp.ver, distance = tmp.dist;
            if (!st[ver]) {
                st[ver] = true;
                for (int i = h[ver]; i != -1; i = ne[i]) {
                    int j = e[i];
                    if (dist[j] > distance + w[i]) {
                        dist[j] = distance + w[i];
                        piis.offer(new PII(dist[j], j));
                    }
                }
            }
        }
        if (dist[n] == 0x3f3f3f3f) {
            return -1;
        } else {
            return dist[n];
        }
    }
}

class PII implements Comparable<PII> {
    int dist, ver;

    public PII(int dist, int ver) {
        this.dist = dist;
        this.ver = ver;
    }

    @Override
    public int compareTo(PII o) {
        return Integer.compare(this.dist, o.dist);
    }
}

